package com.feng.demo.jakartacommons.cli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

/**
 * 这是一个处理处理命令的工具。比如main方法输入的string[]需要解析。你可以预先定义好参数的规则，然后就可以调用CLI来解析。
 * 
 * @author Administrator
 * 
 */
public class CLIDemo {

	public static void main(String args[]) throws IOException {
		CliSelfTest(args);
		//CliTest(args);
	}

	/**
	 * 自己练习实例
	 * @param args
	 * @throws IOException 
	 */
	public static void CliSelfTest(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		try {
			args = in.readLine().split(" ");
			Options opt = new Options();
			opt.addOption("h", false, "Print help for this application");
			opt.addOption("u", true, "The username to use");
			opt.addOption("d", true, "The data source to use");
			BasicParser parser = new BasicParser();
			CommandLine cl = parser.parse(opt, args);
			if (cl.hasOption('h')) {
				HelpFormatter f = new HelpFormatter();
				f.printHelp("OptionsTip", opt);
			} else {
				System.out.println(cl.getOptionValue("u"));
				System.out.println(cl.getOptionValue("d"));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	/**
	 * jakarta 提供的Demo演示
	 * 
	 * @param args
	 */
	public static void CliTest(String[] args) {
		// create the Options object
		Options options = new Options();

		// add the individual options to it by two different ways

		// 1st way is by calling the addOption method on Options object
		options.addOption("n", true, "[name] your name");

		// 2nd way is by creating an Option and then adding it
		Option timeOption = new Option("t", false, "current time");
		timeOption.setRequired(true);
		options.addOption(timeOption);

		// now lets parse the input
		CommandLineParser parser = new BasicParser();
		CommandLine cmd;
		try {
			cmd = parser.parse(options, args);
		} catch (ParseException pe) {
			usage(options);
			return;
		}

		// now lets interrogate the options and execute the relevant parts
		if (cmd.hasOption("t")) {

			System.err.println("Date/Time: " + new java.util.Date());
		}

		if (cmd.hasOption("n")) {

			System.err.println("Nice to meet you: " + cmd.getOptionValue('n'));
		}
	}

	private static void usage(Options options) {

		// Use the inbuilt formatter class
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp("CLIDemo", options);
	}
}